<?php
/**
 * Created by PhpStorm.
 * Author: sitewang@aliyun.com
 * CreateTime: 2022/4/6 5:36 PM
 * Blog：www.myblogs.xyz
 */

namespace App\Http\Controllers\Admin;

use App\Models\Article;
use App\Models\Category;
use App\Services\CommonService;
use Illuminate\Http\Request;

class CategoryController extends CommonController
{
    public function index()
    {
        $category_model = new Category();
        $category_list = $category_model->getList();
        if (!empty($category_list)){
            $article_model = new Article();
            foreach ($category_list as &$val){
                $val->article_count = $article_model->getCount(['cate_id'=>$val->category_id]);
            }
        }
        return view('admin/category', compact('category_list'));
    }

    public function insert()
    {
        $this->getData();
        return view('admin/save_category');
    }

    public function update()
    {
        $this->getData();
        return view('admin/save_category');
    }

    protected function getData()
    {
        $category_id = request('category_id', 0);
        $category_model = new Category();
        $category_list = $category_model->getList();
        $oldData = [];
        if (!empty($category_id)){
            $oldData = $category_model->getFind($category_id);
        }
        if (!empty($category_list)){
            foreach ($category_list as $val){
                $val->is_check = 0;
                if (!empty($oldData) && !empty($oldData->pid)){
                    if ($oldData->pid == $val->category_id){
                        $val->is_check = 1;
                    }
                }
            }
        }
        view()->share([
            'category_list'=>$category_list,
            'oldData'=>$oldData,
        ]);
    }

    public function save(Request $request)
    {
        $data = $request->post();
        if (!empty($data)){
            $category_model = new Category();
            unset($data['_token']);;
            if (empty($data[$category_model->getPrimaryKey()])){
                $data['create_time'] = NEW_TIME;
            }else{
                $data['update_time'] = NEW_TIME;
            }
            $rows = $category_model->operation($data);
            if (!$rows){
                $this->returnError($category_model->getError());
            }
            $this->returnSuccess('保存成功', url('admin/category'));
        }
    }

    public function delete()
    {
        if (CommonService::delete(new Category())){
            $this->returnSuccess('删除成功');
        }
        $this->returnError('删除失败');
    }

}
